package com.rjs.netty;

import com.rjs.netty.docoder.TimeEncoder;
import com.rjs.netty.handler.TimeServerHandler2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Discard any incoming data
 * @author LiuZhenghua
 * 2017年12月19日 上午10:32:39
 */
public class DiscardServer {
	
	private int port;
	
	public DiscardServer(int port) {
		super();
		this.port = port;
	}

	public void run() throws Exception {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
//					ch.pipeline().addLast(new DiscardServerHandler());
//					ch.pipeline().addLast(new EchoServerHandler());
//					ch.pipeline().addLast(new TimeServerHandler());
					ch.pipeline().addLast(new TimeEncoder(), new TimeServerHandler2());
				}
			})
			.option(ChannelOption.SO_BACKLOG, 128)		//标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1，Java将使用默认值50
			.childOption(ChannelOption.SO_KEEPALIVE, true);	//在双方TCP套接字建立连接后（即都进入ESTABLISHED状态）并且在两个小时左右上层没有任何数据传输的情况下，这套机制才会被激活
			
			ChannelFuture f = serverBootstrap.bind(port).sync();
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8777;
        }
        new DiscardServer(port).run();
	}
}
